﻿

using HalconDotNet;
using System.Collections.ObjectModel;
using System;
using ViewROI;
using Prism.Events;
using COVID_19_LiquidFillUI.Common.Services;
using COVID_19_LiquidFillUI.Models;
using NLog;
using System.Threading;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.IO;
using COVID_19_LiquidFillUI.Common.Extensions;
using System.Threading.Tasks;
using System.Linq;
using System.Windows;
using System.Collections.Generic;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
using System.Windows.Documents;

namespace COVID_19_LiquidFillUI.ViewModels
{


    public class Station2ViewModel : BindableBase
    {
        #region 变量
        ICameraService cam0, cam1;
        IPLCModbusService plc;
        public readonly IEventAggregator aggregator;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        CancellationTokenSource source;
        Param param;
        bool plcConnect = false;
        #endregion
        #region 属性绑定
        #region halcon
        #region 1#
        private HImage cameraIamge0;
        public HImage CameraIamge0
        {
            get { return cameraIamge0; }
            set { SetProperty(ref cameraIamge0, value); }
        }
        private bool cameraRepaint0;
        public bool CameraRepaint0
        {
            get { return cameraRepaint0; }
            set { SetProperty(ref cameraRepaint0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        #endregion
        #region 2#
        private HImage cameraIamge1;
        public HImage CameraIamge1
        {
            get { return cameraIamge1; }
            set { SetProperty(ref cameraIamge1, value); }
        }
        private bool cameraRepaint1;
        public bool CameraRepaint1
        {
            get { return cameraRepaint1; }
            set { SetProperty(ref cameraRepaint1, value); }
        }
        private ObservableCollection<ROI> cameraROIList1 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList1
        {
            get { return cameraROIList1; }
            set { SetProperty(ref cameraROIList1, value); }
        }
        private HObject cameraAppendHObject1;
        public HObject CameraAppendHObject1
        {
            get { return cameraAppendHObject1; }
            set { SetProperty(ref cameraAppendHObject1, value); }
        }
        private HMsgEntry cameraAppendHMessage1;
        public HMsgEntry CameraAppendHMessage1
        {
            get { return cameraAppendHMessage1; }
            set { SetProperty(ref cameraAppendHMessage1, value); }
        }
        private Tuple<string, object> cameraGCStyle1;
        public Tuple<string, object> CameraGCStyle1
        {
            get { return cameraGCStyle1; }
            set { SetProperty(ref cameraGCStyle1, value); }
        }
        #endregion
        #endregion
        #endregion
        #region 构造函数
        public Station2ViewModel(IContainerProvider containerProvider, IEventAggregator _aggregator)
        {
            aggregator = _aggregator;
            LoadParam();
            cam0 = containerProvider.Resolve<ICameraService>("Cam2");
            cam1 = containerProvider.Resolve<ICameraService>("Cam3");
            plc = containerProvider.Resolve<IPLCModbusService>("plc");
            var r1 = cam0.OpenCamera(param.Camera3Name);
            if (r1)
            {
                cam0.SetExposureTime(param.Camera3ExposureTime);
                aggregator.SendMessage("Camera2OpenOK", "Camera");
            }
            else
            {
                aggregator.SendMessage("Camera2OpenNG", "Camera");
            }
            var r2 = cam1.OpenCamera(param.Camera4Name);
            if (r2)
            {
                cam1.SetExposureTime(param.Camera4ExposureTime);
                aggregator.SendMessage("Camera3OpenOK", "Camera");
            }
            else
            {
                aggregator.SendMessage("Camera3OpenNG", "Camera");
            }
            if (r1 && r2)
            {
                source = new CancellationTokenSource();
                CancellationToken token1 = source.Token;
                Task.Run(() => Run(token1), token1);
            }
            aggregator.ResgiterMessage(arg => {
                switch (arg.Message)
                {
                    case "Closed":
                        if (source != null)
                        {
                            source.Cancel();
                        }
                        break;
                    case "PLCConnect":
                        plcConnect = true;
                        break;
                    default:
                        break;
                }
            }, "App");
        }
        #endregion
        #region 功能函数
        private void Run(CancellationToken token)
        {
            List<MJudgeCalc> mJudgeCalcList = new List<MJudgeCalc>();
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                try
                {
                    if (plcConnect)
                    {
                        var m710 = plc.ReadMCoils(710, 1);
                        if (m710 != null)
                        {
                            if (m710[0])
                            {
                                aggregator.SendMessage("工位2触发拍照。", "Message");
                                plc.WriteMCoil(710, false);

                                var img0 = cam0.GrabImage();
                                CameraIamge0 = img0;
                                var img1 = cam1.GrabImage();
                                CameraIamge1 = img1;
                                if (param.IsSaveImage)
                                {
                                    try
                                    {
                                        string filepath = $"SaveImage\\2\\{DateTime.Now:yyyyMMdd}";
                                        DirectoryInfo dir = new DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                                        if (!dir.Exists)
                                        {
                                            Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                                        }
                                        HOperatorSet.WriteImage(img0, "jpeg", 0, System.IO.Path.Combine(System.Environment.CurrentDirectory, filepath, $"{DateTime.Now:yyyyMMddHHmmss}.jpg"));
                                        filepath = $"SaveImage\\3\\{DateTime.Now:yyyyMMdd}";
                                        dir = new DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                                        if (!dir.Exists)
                                        {
                                            Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                                        }
                                        HOperatorSet.WriteImage(img1, "jpeg", 0, System.IO.Path.Combine(System.Environment.CurrentDirectory, filepath, $"{DateTime.Now:yyyyMMddHHmmss}.jpg"));
                                    }
                                    catch (Exception ex)
                                    {
                                        aggregator.SendMessage(ex.Message, "Message");
                                    }
                                }
                                #region 计算图像1
                                bool totalResult1 = true;
                                var mdb = new MDbContext();
                                if (img0 != null)
                                {

                                    string filepath = $"Camera\\2";

                                    HObject rec1_region;
                                    HOperatorSet.ReadRegion(out rec1_region, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                                    HTuple ModelThresholdMax;
                                    HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ModelThresholdMax.tup"), out ModelThresholdMax);
                                    HObject ho_ResultRegion;
                                    HTuple hv_Row, hv_Column;
                                    ImageCalc.FindModel(img0, rec1_region, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);

                                    if (hv_Row.D != 0)
                                    {
                                        HTuple ST_Row, ST_Column;
                                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"), out ST_Row);
                                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"), out ST_Column);

                                        HTuple HomMat2D;
                                        HOperatorSet.VectorAngleToRigid(ST_Row, ST_Column, 0, hv_Row, hv_Column, 0, out HomMat2D);

                                        #region 判断有无
                                        var points0 = mdb.MVisionPoint2s.Where(p => p.Kind == 2);
                                        if (points0.Any())
                                        {
                                            var points1 = points0.OrderBy(p => p.PcsOrder).ToList();
                                            foreach (var item in points1)
                                            {
                                                try
                                                {
                                                    HObject rec0;
                                                    HOperatorSet.ReadRegion(out rec0, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{item.PcsOrder}.hobj"));
                                                    HObject rec1;
                                                    HOperatorSet.AffineTransRegion(rec0,out rec1, HomMat2D, "nearest_neighbor");

                                                    HObject ho_resultRegion; HTuple hv_result, mArea;
                                                    ImageCalc.AreaCalc(img0, rec1, item.ThresholdMin, item.ThresholdMax, item.JudgeArea, out ho_resultRegion, out hv_result, out mArea);

                                                    HTuple msgRow, mesColumn;
                                                    HOperatorSet.RegionFeatures(rec1, "row", out msgRow);
                                                    HOperatorSet.RegionFeatures(rec1, "column", out mesColumn);
                                                    if (hv_result != 1)
                                                    {
                                                        totalResult1 = false;
                                                        aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断有无:{mArea.D:f1}<{item.JudgeArea},失败", "Message");
                                                    }
                                                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                                    {

                                                        //CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)msgRow.D, (int)mesColumn.D, "black", "image", "box", "true", 12, "mono", "true", "false");
                                                        //
                                                        if (hv_result == 1)
                                                        {
                                                            CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                                                            CameraAppendHObject0 = ho_resultRegion;
                                                        }
                                                        else
                                                        {
                                                            CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                                                            CameraAppendHObject0 = rec1;
                                                        }
                                                        
                                                    }));
                                                }
                                                catch (Exception ex)
                                                {
                                                    logger.Error(ex);
                                                    totalResult1 = false;
                                                    aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断有无:{ex.Message},失败", "Message");
                                                }

                                            }
                                        }
                                        #endregion
                                        #region 新载具无需判断半径及圆心距离
                                        //#region 判断半径
                                        //mJudgeCalcList.Clear();
                                        //var drawcircle0 = mdb.MDrawCircles.Where(p => p.Kind == 2);
                                        //if (drawcircle0.Any())
                                        //{
                                        //    var drawcircle1 = drawcircle0.OrderBy(p => p.PcsOrder).ToList();
                                        //    foreach (var item in drawcircle1)
                                        //    {
                                        //        try
                                        //        {
                                        //            HTuple row1, column1;
                                        //            HOperatorSet.AffineTransPoint2d(HomMat2D, item.Row, item.Column, out row1, out column1);//偏置后的圆心位置
                                        //            HTuple hv_ResutlRow, hv_ResultColumn, hv_ResultRadius;
                                        //            ImageCalc.FindCircle(img0, row1, column1, item.Radius, item.MeasureThrehold,
                                        //                out hv_ResutlRow, out hv_ResultColumn, out hv_ResultRadius);

                                        //            if (hv_ResutlRow != null)
                                        //            {
                                        //                if (hv_ResultRadius.D < item.ST_RadiusMin || hv_ResultRadius.D > item.ST_RadiusMax)
                                        //                {
                                        //                    totalResult1 = false;
                                        //                    aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断半径:{hv_ResultRadius.D:f1},最小({item.ST_RadiusMin}),最大({item.ST_RadiusMax}),失败", "Message");
                                        //                }
                                        //                mJudgeCalcList.Add(new MJudgeCalc
                                        //                {
                                        //                    PcsOrder = item.PcsOrder,
                                        //                    Row = hv_ResutlRow,
                                        //                    Column = hv_ResultColumn
                                        //                });
                                        //            }
                                        //            else
                                        //            {
                                        //                totalResult1 = false;
                                        //                aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断半径:未找到圆,失败", "Message");
                                        //            }

                                        //            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                        //            {
                                        //                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                                        //                if (hv_ResutlRow != null)
                                        //                {
                                        //                    HObject ho_ResultCircle;
                                        //                    HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResutlRow, hv_ResultColumn, hv_ResultRadius);
                                        //                    CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                        //                    CameraAppendHObject0 = ho_ResultCircle;
                                        //                    if (hv_ResultRadius.D < item.ST_RadiusMin || hv_ResultRadius.D > item.ST_RadiusMax)
                                        //                    {
                                        //                        CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                                        //                    }
                                        //                }
                                        //                else
                                        //                {
                                        //                    HObject ho_ResultCircle;
                                        //                    HOperatorSet.GenCircle(out ho_ResultCircle, row1, column1, item.Radius);
                                        //                    CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                        //                    CameraAppendHObject0 = ho_ResultCircle;
                                        //                    CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                                        //                }
                                        //            }));
                                        //        }
                                        //        catch (Exception ex)
                                        //        {
                                        //            logger.Error(ex);
                                        //            totalResult1 = false;
                                        //            aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断半径:{ex.Message},失败", "Message");
                                        //        }
                                        //    }
                                        //}
                                        //#endregion
                                        //#region 判断圆心距离
                                        //if (mJudgeCalcList.Any())
                                        //{
                                        //    var judge0 = mdb.MJudges.Where(p => p.Kind == 2);
                                        //    if (judge0.Any())
                                        //    {
                                        //        var judge1 = judge0.OrderBy(p => p.PcsOrder).ToList();
                                        //        foreach (var item in judge1)
                                        //        {
                                        //            try
                                        //            {
                                        //                var circle0 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex0);
                                        //                var circle1 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex1);
                                        //                if (circle0 != null && circle1 != null)
                                        //                {
                                        //                    HTuple dist;
                                        //                    HOperatorSet.DistancePp(circle0.Row, circle0.Column, circle1.Row, circle1.Column, out dist);
                                        //                    HObject line;
                                        //                    HOperatorSet.GenRegionLine(out line, circle0.Row, circle0.Column, circle1.Row, circle1.Column);
                                        //                    if (dist.D < item.ST_DistMin || dist.D > item.ST_DistMax)
                                        //                    {
                                        //                        totalResult1 = false;
                                        //                        aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断圆心距:圆({item.CircleIndex0})-圆({item.CircleIndex1}):{dist.D:f1},最小{item.ST_DistMin},最大{item.ST_DistMax},失败", "Message");
                                        //                    }
                                        //                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                        //                    {
                                        //                        if (dist.D >= item.ST_DistMin && dist.D <= item.ST_DistMax)
                                        //                        {
                                        //                            CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                        //                        }
                                        //                        else
                                        //                        {
                                        //                            CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                        //                        }
                                        //                        CameraAppendHObject0 = line;
                                        //                    }));
                                        //                }
                                        //                else
                                        //                {
                                        //                    totalResult1 = false;
                                        //                }
                                        //            }
                                        //            catch (Exception ex)
                                        //            {
                                        //                logger.Error(ex);
                                        //                totalResult1 = false;
                                        //                aggregator.SendMessage($"工位2相机3:[{item.PcsOrder}]判断圆心距:{ex.Message},失败", "Message");
                                        //            }
                                        //        }
                                        //    }
                                        //}
                                        //#endregion
                                        #endregion
                                    }
                                    else
                                    {
                                        aggregator.SendMessage("相机3未找到模板。", "Message");
                                        totalResult1 = false;
                                    }
                                }
                                else
                                {
                                    totalResult1 = false;
                                }
                                #endregion
                                #region 计算图像2
                                bool totalResult2 = true;
                                if (img1 != null)
                                {
                                    string filepath = $"Camera\\3";

                                    HObject rec1_region;
                                    HOperatorSet.ReadRegion(out rec1_region, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                                    HTuple ModelThresholdMax;
                                    HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ModelThresholdMax.tup"), out ModelThresholdMax);
                                    HObject ho_ResultRegion;
                                    HTuple hv_Row, hv_Column;
                                    ImageCalc.FindModel(img1, rec1_region, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);

                                    if (hv_Row.D != 0)
                                    {
                                        HTuple ST_Row, ST_Column;
                                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"), out ST_Row);
                                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"), out ST_Column);

                                        HTuple HomMat2D;
                                        HOperatorSet.VectorAngleToRigid(ST_Row, ST_Column, 0, hv_Row, hv_Column, 0, out HomMat2D);

                                        #region 判断有无
                                        var points0 = mdb.MVisionPoint2s.Where(p => p.Kind == 3);
                                        if (points0.Any())
                                        {
                                            var points1 = points0.OrderBy(p => p.PcsOrder).ToList();
                                            foreach (var item in points1)
                                            {
                                                try
                                                {
                                                    HObject rec0;
                                                    HOperatorSet.ReadRegion(out rec0, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{item.PcsOrder}.hobj"));
                                                    HObject rec1;
                                                    HOperatorSet.AffineTransRegion(rec0, out rec1, HomMat2D, "nearest_neighbor");

                                                    HObject ho_resultRegion; HTuple hv_result, mArea;
                                                    ImageCalc.AreaCalc(img1, rec1, item.ThresholdMin, item.ThresholdMax, item.JudgeArea, out ho_resultRegion, out hv_result, out mArea);

                                                    HTuple msgRow, mesColumn;
                                                    HOperatorSet.RegionFeatures(rec1, "row", out msgRow);
                                                    HOperatorSet.RegionFeatures(rec1, "column", out mesColumn);
                                                    if (hv_result != 1)
                                                    {
                                                        totalResult2 = false;
                                                        aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断有无:{mArea.D:f1}<{item.JudgeArea},失败", "Message");
                                                    }
                                                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                                    {

                                                        //CameraAppendHMessage1 = new HMsgEntry($"{item.PcsOrder}", (int)msgRow.D, (int)mesColumn.D, "black", "image", "box", "true", 12, "mono", "true", "false");                                                   
                                                        
                                                        if (hv_result == 1)
                                                        {
                                                            CameraGCStyle1 = new Tuple<string, object>("Color", "green");
                                                            CameraGCStyle1 = new Tuple<string, object>("DrawMode", "fill");
                                                            CameraAppendHObject1 = ho_resultRegion;
                                                        }
                                                        else
                                                        {
                                                            CameraGCStyle1 = new Tuple<string, object>("Color", "red");
                                                            CameraGCStyle1 = new Tuple<string, object>("DrawMode", "margin");
                                                            CameraAppendHObject1 = rec1;
                                                        }
                                                        
                                                    }));
                                                }
                                                catch (Exception ex)
                                                {
                                                    logger.Error(ex);
                                                    totalResult2 = false;
                                                    aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断有无:{ex.Message},失败", "Message");
                                                }

                                            }
                                        }
                                        #endregion
                                        #region 新载具无需判断半径及圆心距离
                                        //#region 判断半径
                                        //mJudgeCalcList.Clear();
                                        //var drawcircle0 = mdb.MDrawCircles.Where(p => p.Kind == 3);
                                        //if (drawcircle0.Any())
                                        //{
                                        //    var drawcircle1 = drawcircle0.OrderBy(p => p.PcsOrder).ToList();
                                        //    foreach (var item in drawcircle1)
                                        //    {
                                        //        try
                                        //        {
                                        //            HTuple row1, column1;
                                        //            HOperatorSet.AffineTransPoint2d(HomMat2D, item.Row, item.Column, out row1, out column1);//偏置后的圆心位置
                                        //            HTuple hv_ResutlRow, hv_ResultColumn, hv_ResultRadius;
                                        //            ImageCalc.FindCircle(img1, row1, column1, item.Radius, item.MeasureThrehold,
                                        //                out hv_ResutlRow, out hv_ResultColumn, out hv_ResultRadius);

                                        //            if (hv_ResutlRow != null)
                                        //            {
                                        //                if (hv_ResultRadius.D < item.ST_RadiusMin || hv_ResultRadius.D > item.ST_RadiusMax)
                                        //                {
                                        //                    totalResult2 = false;
                                        //                    aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断半径:{hv_ResultRadius.D:f1},最小({item.ST_RadiusMin}),最大({item.ST_RadiusMax}),失败", "Message");
                                        //                }
                                        //                mJudgeCalcList.Add(new MJudgeCalc
                                        //                {
                                        //                    PcsOrder = item.PcsOrder,
                                        //                    Row = hv_ResutlRow,
                                        //                    Column = hv_ResultColumn
                                        //                });
                                        //            }
                                        //            else
                                        //            {
                                        //                totalResult2 = false;
                                        //                aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断半径:未找到圆,失败", "Message");
                                        //            }

                                        //            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                        //            {
                                        //                CameraGCStyle1 = new Tuple<string, object>("DrawMode", "margin");
                                        //                if (hv_ResutlRow != null)
                                        //                {
                                        //                    HObject ho_ResultCircle;
                                        //                    HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResutlRow, hv_ResultColumn, hv_ResultRadius);
                                        //                    CameraGCStyle1 = new Tuple<string, object>("Color", "green");
                                        //                    CameraAppendHObject1 = ho_ResultCircle;
                                        //                    if (hv_ResultRadius.D < item.ST_RadiusMin || hv_ResultRadius.D > item.ST_RadiusMax)
                                        //                    {
                                        //                        CameraAppendHMessage1 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                                        //                    }
                                        //                }
                                        //                else
                                        //                {
                                        //                    HObject ho_ResultCircle;
                                        //                    HOperatorSet.GenCircle(out ho_ResultCircle, row1, column1, item.Radius);
                                        //                    CameraGCStyle1 = new Tuple<string, object>("Color", "red");
                                        //                    CameraAppendHObject1 = ho_ResultCircle;
                                        //                    CameraAppendHMessage1 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                                        //                }
                                        //            }));
                                        //        }
                                        //        catch (Exception ex)
                                        //        {
                                        //            logger.Error(ex);
                                        //            totalResult2 = false;
                                        //            aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断半径:{ex.Message},失败", "Message");
                                        //        }
                                        //    }
                                        //}
                                        //#endregion
                                        //#region 判断圆心距离
                                        //if (mJudgeCalcList.Any())
                                        //{
                                        //    var judge0 = mdb.MJudges.Where(p => p.Kind == 3);
                                        //    if (judge0.Any())
                                        //    {
                                        //        var judge1 = judge0.OrderBy(p => p.PcsOrder).ToList();
                                        //        foreach (var item in judge1)
                                        //        {
                                        //            try
                                        //            {
                                        //                var circle0 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex0);
                                        //                var circle1 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex1);
                                        //                if (circle0 != null && circle1 != null)
                                        //                {
                                        //                    HTuple dist;
                                        //                    HOperatorSet.DistancePp(circle0.Row, circle0.Column, circle1.Row, circle1.Column, out dist);
                                        //                    HObject line;
                                        //                    HOperatorSet.GenRegionLine(out line, circle0.Row, circle0.Column, circle1.Row, circle1.Column);
                                        //                    if (dist.D < item.ST_DistMin || dist.D > item.ST_DistMax)
                                        //                    {
                                        //                        totalResult2 = false;
                                        //                        aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断圆心距:圆({item.CircleIndex0})-圆({item.CircleIndex1}):{dist.D:f1},最小{item.ST_DistMin},最大{item.ST_DistMax},失败", "Message");
                                        //                    }
                                        //                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                        //                    {
                                        //                        if (dist.D >= item.ST_DistMin && dist.D <= item.ST_DistMax)
                                        //                        {
                                        //                            CameraGCStyle1 = new Tuple<string, object>("Color", "green");
                                        //                        }
                                        //                        else
                                        //                        {
                                        //                            CameraGCStyle1 = new Tuple<string, object>("Color", "red");
                                        //                        }
                                        //                        CameraAppendHObject1 = line;
                                        //                    }));
                                        //                }
                                        //                else
                                        //                {
                                        //                    totalResult2 = false;
                                        //                }
                                        //            }
                                        //            catch (Exception ex)
                                        //            {
                                        //                logger.Error(ex);
                                        //                totalResult2 = false;
                                        //                aggregator.SendMessage($"工位2相机4:[{item.PcsOrder}]判断圆心距:{ex.Message},失败", "Message");
                                        //            }
                                        //        }
                                        //    }
                                        //}
                                        //#endregion
                                        #endregion
                                    }
                                    else
                                    {
                                        aggregator.SendMessage("相机4未找到模板。", "Message");
                                        totalResult2 = false;
                                    }
                                }
                                else
                                {
                                    totalResult2 = false;
                                }
                                #endregion

                                if (totalResult1 && totalResult2)
                                {
                                    plc.WriteMCoil(712, true);
                                }
                                else
                                {
                                    plc.WriteMCoil(713, true);
                                }

                                plc.WriteMCoil(711, true);
                                System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                                {
                                    if (totalResult1)
                                    {
                                        CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                                    }
                                    else
                                    {
                                        CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                                    }
                                    if (totalResult2)
                                    {
                                        CameraAppendHMessage1 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                                    }
                                    else
                                    {
                                        CameraAppendHMessage1 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                                    }
                                }));
                            }
                        }
                    }
                }
                catch { }
                Thread.Sleep(100);
            }
        }
        private void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                param = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

        }
        #endregion
    }

}
